﻿using System;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using HelfenHelfen.Web.Forms.Site.Utility;

namespace HelfenHelfen.Web.Forms.Site {
   public partial class Login : System.Web.UI.Page {
      protected global::System.Web.UI.WebControls.Label                 ctlErrorDetails;
      protected global::System.Web.UI.HtmlControls.HtmlContainerControl ctlErrorDiv; 

      protected void Page_Load(object sender, EventArgs e) {
         // initialize variables
         ctlErrorDetails = (Label)ctlLogin.FindControlRecursive("LoginErrorDetails");
         ctlErrorDiv = (HtmlContainerControl) this.FindControlRecursive("divError");

         if (Page.Request.IsAuthenticated)
            Response.Redirect("Default.aspx");

         // we need to set the visibility of our Error Summary manually
         ctlErrorDiv.Attributes.CssStyle.Add("display", "none");

         if (IsPostBack) {
            Validate();
            if (!IsValid) {
               ctlErrorDiv.Attributes.CssStyle.Add("display", "block");
               ctlErrorDetails.Visible = true;
               ctlErrorDetails.Style.Add("display", "block");
            }
         }
      }


      // See http://www.4guysfromrolla.com/articles/050306-1.aspx
      protected void OnLoginError(object sender, EventArgs e) {
         //See if this user exists in the database
         MembershipUser userInfo = Membership.GetUser(ctlLogin.UserName);
         ctlErrorDiv.Attributes.CssStyle.Add("display", "block");
         if (userInfo == null) {
            //The user entered an invalid username...
            this.ctlErrorDetails.Text = "There is no user in the database with the username " + ctlLogin.UserName;
         }
         else {
            //See if the user is locked out or not approved
            if (!userInfo.IsApproved) {
               ctlErrorDetails.Text = "Your account has not yet been approved by the site's administrators. Please try again later...";
            }
            else {
               if (userInfo.IsLockedOut) {
                  ctlErrorDetails.Text = "Your account has been locked out because of a maximum number of incorrect login attempts. You will NOT be able to login until you contact a site administrator and have your account unlocked.";
               }
               else {
                  //The password was incorrect (don't show anything, the Login control already describes the problem)
                  // LoginErrorDetails.Text = String.Empty;
                  ctlErrorDetails.Text = "Your login attempt was not successful. Please try again.";
               }
            }
         }
      }
   }
}